<template>
  <div class="record-management-container">
    <el-card class="page-header-card">
      <div class="page-header">
        <div class="page-title">
          <h2>出入场信息管理</h2>
          <p>管理车辆进出记录，查看停车费用</p>
        </div>
      </div>
    </el-card>
    
    <!-- 搜索表单 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="车牌号">
          <el-input v-model="searchForm.plateNumber" placeholder="请输入车牌号" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="进行中" :value="0" />
            <el-option label="已完成" :value="1" />
            <el-option label="异常" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="支付状态">
          <el-select v-model="searchForm.isPaid" placeholder="请选择支付状态" clearable>
            <el-option label="未支付" :value="0" />
            <el-option label="已支付" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 实时统计 -->
    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6" v-for="(card, index) in dataCards" :key="index">
        <el-card class="data-card" :class="card.type">
          <div class="card-icon">
            <el-icon>
              <van v-if="card.icon === 'Van'" />
              <timer v-else-if="card.icon === 'Timer'" />
              <money v-else-if="card.icon === 'Money'" />
              <box v-else-if="card.icon === 'Box'" />
            </el-icon>
          </div>
          <div class="card-info">
            <div class="card-title">{{ card.title }}</div>
            <div class="card-value">{{ card.value }}</div>
            <div class="card-desc">{{ card.desc }}</div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 停车记录列表 -->
    <el-card class="table-card" style="margin-top: 20px;">
      <template #header>
        <div class="card-header">
          <span>停车记录列表</span>
        </div>
      </template>
      
      <el-table
        :data="recordList"
        style="width: 100%"
        border
        v-loading="loading"
        @row-click="handleRowClick"
        row-key="id"
      >
        <el-table-column prop="id" label="记录ID" width="90" />
        <el-table-column prop="plateNumber" label="车牌号码" width="120" />
        <el-table-column prop="spaceNumber" label="车位号" width="100" />
        <el-table-column prop="entryTime" label="入场时间" width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.entryTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="exitTime" label="出场时间" width="180">
          <template #default="scope">
            {{ scope.row.exitTime ? formatDateTime(scope.row.exitTime) : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="停车时长" min-width="100">
          <template #default="scope">
            {{ calculateDuration(scope.row.entryTime, scope.row.exitTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="parkingFee" label="停车费用" width="110">
          <template #default="scope">
            {{ scope.row.parkingFee != null ? `¥${scope.row.parkingFee.toFixed(2)}` : '未结算' }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="isPaid" label="支付状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.isPaid === 1 ? 'success' : 'warning'">
              {{ scope.row.isPaid === 1 ? '已支付' : '未支付' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="scope">
            <el-button 
              v-if="scope.row.status === 0" 
              type="primary" 
              size="small" 
              @click.stop="handleExit(scope.row)"
            >
              登记出场
            </el-button>
            <el-button 
              type="info" 
              size="small" 
              @click.stop="handleDetail(scope.row)"
            >
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailVisible"
      title="停车记录详情"
      width="600px"
    >
      <div v-if="selectedRecord" class="record-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="记录ID">{{ selectedRecord.id }}</el-descriptions-item>
          <el-descriptions-item label="车牌号码">{{ selectedRecord.plateNumber }}</el-descriptions-item>
          <el-descriptions-item label="车位号">{{ selectedRecord.spaceNumber }}</el-descriptions-item>
          <el-descriptions-item label="入场时间">{{ formatDateTime(selectedRecord.entryTime) }}</el-descriptions-item>
          <el-descriptions-item label="出场时间">
            {{ selectedRecord.exitTime ? formatDateTime(selectedRecord.exitTime) : '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="停车时长">
            {{ calculateDuration(selectedRecord.entryTime, selectedRecord.exitTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="停车费用">
            {{ selectedRecord.parkingFee != null ? `¥${selectedRecord.parkingFee.toFixed(2)}` : '未结算' }}
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusType(selectedRecord.status)">
              {{ getStatusText(selectedRecord.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="支付状态">
            <el-tag :type="selectedRecord.isPaid === 1 ? 'success' : 'warning'">
              {{ selectedRecord.isPaid === 1 ? '已支付' : '未支付' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间" :span="2">
            {{ formatDateTime(selectedRecord.createdAt) }}
          </el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">
            {{ selectedRecord.remark || '-' }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>
    
    <!-- 出场对话框 -->
    <el-dialog
      v-model="exitVisible"
      title="登记出场"
      width="500px"
    >
      <div v-if="selectedRecord" class="exit-form">
        <el-form :model="exitForm" label-width="100px">
          <el-form-item label="车牌号码">
            <span>{{ selectedRecord.plateNumber }}</span>
          </el-form-item>
          <el-form-item label="入场时间">
            <span>{{ formatDateTime(selectedRecord.entryTime) }}</span>
          </el-form-item>
          <el-form-item label="停车时长">
            <span>{{ calculateDuration(selectedRecord.entryTime, new Date()) }}</span>
          </el-form-item>
          <el-form-item label="备注">
            <el-input
              v-model="exitForm.remark"
              type="textarea"
              :rows="3"
              placeholder="请输入备注信息"
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="exitVisible = false">取消</el-button>
          <el-button type="primary" @click="handleExitConfirm" :loading="exitLoading">
            确认出场
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, RefreshRight, Download, Printer, View, Van, Timer, Money, Box, ArrowUp, ArrowDown } from '@element-plus/icons-vue'
import { getParkingRecordList, getParkingRecordDetail, manualExitRecord } from '@/api/system'
import { formatDateTime } from '@/utils/format'

// 数据卡片
const dataCards = computed(() => [
  {
    title: '总停车记录',
    value: total.value || 0,
    desc: '累计停车记录数',
    type: 'primary',
    icon: 'Van'
  },
  {
    title: '当前在场',
    value: recordList.value.filter(record => record.status === 0).length || 0,
    desc: '正在停车的车辆数',
    type: 'success',
    icon: 'Timer'
  },
  {
    title: '待支付记录',
    value: recordList.value.filter(record => record.isPaid === 0).length || 0,
    desc: '未完成支付的记录',
    type: 'warning',
    icon: 'Money'
  },
  {
    title: '异常记录',
    value: recordList.value.filter(record => record.status === 2).length || 0,
    desc: '需要处理的异常记录',
    type: 'danger',
    icon: 'Box'
  }
])

// 状态选项
const statusOptions = [
  { value: 0, label: '进行中' },
  { value: 1, label: '已完成' },
  { value: 2, label: '异常' }
]

// 区域选项
const areaOptions = [
  { value: 'A区', label: 'A区' },
  { value: 'B区', label: 'B区' },
  { value: 'C区', label: 'C区' },
  { value: 'D区', label: 'D区' }
]

// 加载状态
const loading = ref(false)

// 分页参数
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 搜索表单
const searchForm = ref({
  plateNumber: '',
  status: '',
  isPaid: ''
})

// 数据卡片

// 停车记录列表数据
const recordList = ref([])

// 当前查看的记录详情
const selectedRecord = ref(null)

// 对话框控制
const detailVisible = ref(false)
const exitVisible = ref(false)
const exitLoading = ref(false)

// 出场表单
const exitForm = ref({
  remark: ''
})

// 生命周期钩子
onMounted(() => {
  fetchRecords()
})

// 获取停车记录列表
const fetchRecords = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      ...searchForm.value
    }
    const response = await getParkingRecordList(params)
    if (response.code === 200) {
      recordList.value = response.data.records || []
      total.value = response.data.total || 0
    } else {
      ElMessage.error(response.message || '获取停车记录列表失败')
    }
  } catch (error) {
    console.error('获取停车记录列表失败:', error)
    ElMessage.error('获取停车记录列表失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 获取状态标签类型
const getStatusType = (status) => {
  const types = {
    0: 'primary',  // 进行中
    1: 'success',  // 已完成
    2: 'danger'    // 异常
  }
  return types[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const texts = {
    0: '进行中',
    1: '已完成',
    2: '异常'
  }
  return texts[status] || '未知状态'
}

// 计算停车时长
const calculateDuration = (startTime, endTime) => {
  if (!startTime) return '-'
  
  const start = new Date(startTime)
  const end = endTime ? new Date(endTime) : new Date()
  
  const diffMs = end - start
  const diffMinutes = Math.floor(diffMs / 60000)
  
  if (diffMinutes < 60) {
    return `${diffMinutes} 分钟`
  }
  
  const hours = Math.floor(diffMinutes / 60)
  const minutes = diffMinutes % 60
  
  if (hours < 24) {
    return `${hours} 小时 ${minutes} 分钟`
  }
  
  const days = Math.floor(hours / 24)
  const remainingHours = hours % 24
  
  return `${days} 天 ${remainingHours} 小时 ${minutes} 分钟`
}

// 计算停车费用（模拟）
const calculateFee = (startTime, endTime) => {
  if (!startTime || !endTime) return 0
  
  const start = new Date(startTime)
  const end = new Date(endTime)
  
  const diffMs = end - start
  const diffHours = diffMs / 3600000
  
  // 模拟计算逻辑：前1小时免费，之后每小时5元，封顶50元/天
  if (diffHours <= 1) {
    return 0
  }
  
  const fee = Math.min(Math.ceil(diffHours - 1) * 5, 50)
  return fee
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchRecords()
}

// 重置搜索
const handleReset = () => {
  searchForm.value = {
    plateNumber: '',
    status: '',
    isPaid: ''
  }
  handleSearch()
}

// 处理行点击事件
const handleRowClick = (row) => {
  handleDetail(row)
}

// 处理查看详情
const handleDetail = (row) => {
  selectedRecord.value = row
  detailVisible.value = true
}

// 查看支付详情
const viewPaymentDetail = (paymentId) => {
  ElMessage.info(`查看支付订单：${paymentId}`)
  // 实际项目中应跳转到支付详情页或打开支付详情对话框
}

// 处理手动出场
const handleExit = (row) => {
  selectedRecord.value = row
  exitForm.value.remark = ''
  exitVisible.value = true
}

// 提交手动出场
const handleExitConfirm = async () => {
  if (!selectedRecord.value) return
  
  exitLoading.value = true
  try {
    const exitData = {
      id: selectedRecord.value.id,
      exitTime: new Date().toISOString().slice(0, 19).replace('T', ' '), // 格式化为 YYYY-MM-DD HH:mm:ss
      remark: exitForm.value.remark || undefined
    }
    
    const response = await manualExitRecord(exitData)
    if (response.code === 200) {
      ElMessage.success(`已为车辆【${selectedRecord.value.plateNumber}】登记出场`)
      // 刷新列表
      fetchRecords()
      // 关闭对话框
      exitVisible.value = false
      detailVisible.value = false
    } else {
      ElMessage.error(response.message || '登记出场失败')
    }
  } catch (error) {
    console.error('登记出场失败:', error)
    ElMessage.error('登记出场失败，请稍后重试')
  } finally {
    exitLoading.value = false
  }
}

// 导出数据
const handleExport = () => {
  ElMessage.success('数据导出成功')
  // 实际项目中应调用API导出数据
}

// 打印列表
const handlePrint = () => {
  ElMessage.success('打印任务已发送')
  // 实际项目中应调用打印功能
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchRecords()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchRecords()
}
</script>

<style scoped>
.record-management-container {
  padding: 20px;
  min-height: calc(100vh - 180px);
}

.page-header-card {
  margin-bottom: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-title h2 {
  margin: 0 0 5px 0;
  font-size: 22px;
}

.page-title p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.data-card {
  display: flex;
  align-items: center;
  padding: 20px;
  margin-bottom: 20px;
}

.data-card.primary {
  border-left: 4px solid #409EFF;
}

.data-card.success {
  border-left: 4px solid #67C23A;
}

.data-card.warning {
  border-left: 4px solid #E6A23C;
}

.data-card.danger {
  border-left: 4px solid #F56C6C;
}

.card-icon {
  font-size: 48px;
  margin-right: 16px;
  color: #909399;
}

.card-info {
  flex: 1;
}

.card-title {
  font-size: 14px;
  color: #606266;
  margin-bottom: 5px;
}

.card-value {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 5px;
}

.card-desc {
  font-size: 12px;
  color: #909399;
}

.table-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.fee-text {
  font-weight: bold;
  margin-right: 10px;
}

.fee-unpaid {
  color: #F56C6C;
}

.action-buttons {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.exit-info {
  background-color: #f5f7fa;
  border-radius: 4px;
  padding: 15px;
  margin: 10px 0;
}

.exit-info p {
  margin: 5px 0;
}

.record-detail {
  padding: 20px;
}

.exit-form {
  padding: 20px;
}

@media screen and (max-width: 992px) {
  .data-card {
    margin-bottom: 15px;
  }
}

@media screen and (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .page-actions {
    margin-top: 15px;
    width: 100%;
  }
  
  .search-form {
    display: flex;
    flex-direction: column;
  }
  
  .search-form .el-form-item {
    margin-right: 0;
    width: 100%;
  }
  
  .card-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .header-actions {
    margin-top: 10px;
    display: flex;
    width: 100%;
  }
  
  .header-actions .el-button {
    flex: 1;
  }
  
  .pagination-container {
    justify-content: center;
  }
  
  .dialog-footer {
    flex-direction: column;
    gap: 10px;
  }
  
  .dialog-footer .el-button {
    width: 100%;
  }
  
  .exit-info {
    font-size: 14px;
  }
}

@media screen and (max-width: 576px) {
  .record-management-container {
    padding: 10px;
  }
  
  .search-card, .table-card {
    margin-bottom: 10px;
  }
  
  .el-date-picker {
    width: 100% !important;
  }
  
  .el-descriptions__label {
    width: 100px;
  }
  
  .data-card {
    padding: 10px;
  }
  
  .card-icon {
    font-size: 36px;
  }
  
  .card-value {
    font-size: 20px;
  }
}
</style> 